<?php

namespace app\admin\controller;

use think\Controller;
use think\Db;
use think\Exception;
use think\facade\Validate;
use think\Paginator;

class Admin extends Controller
{
    // 管理员个人信息
    public function adminInfo()
    {
        if (request()->isAjax()) {
            $data = [
                'id' => input('id'),
                'password' => input('password'),
                'nickname' => input('nickname')
            ];
            $validate = Validate::make([
                'nickname|昵称' => 'require'
            ]);
            if (!$validate->check($data)) {
                $this->result('', 0, $validate->getError(), 'json');
            } else {
                $updateData = [
                    'id' => $data['id'],
                    'nickname' => $data['nickname']
                ];
                if ($data['password']) {
                    $updateData['password'] = md5($data['password']);
                }
                Db::startTrans();
                try {
                    model('Admin')::update($updateData);
                    Db::commit();
                } catch (Exception $e) {
                    Db::rollback();
                    $this->result('', 0, $e->getMessage(), 'json');
                }
                $this->result('', 1, '操作成功', 'json');
            }
        }
        $adminInfo = model('Admin')::get(session('adminId'));
        $viewData = [
            'adminInfo' => $adminInfo
        ];
        $this->assign($viewData);
        return view();
    }

    // 管理员列表
    public function adminList()
    {
        if (request()->isPost()) {
            $data = [
                'username' => input('username'),
                'nickname' => input('nickname'),
                'limit' => input('limit'),
                'page' => input('page')
            ];
            $where = $order = [];
            if ($data['nickname']) {
                $where[] = ['nickname', 'like', '%' . $data['nickname'] . '%'];
            }
            if ($data['username']) {
                $where[] = ['username', 'like', '%' . $data['username'] . '%'];
            }
            $order['create_time'] = 'desc';
            $list = model('Admin')::where($where)->withAttr([
                'group_name' => function ($value, $info) {
                    $groupId = model('AuthGroupAccess')::where('uid', $info['id'])->value('group_id');
                    if ($groupId) {
                        $groupName = model('AuthGroup')::where('id', $groupId)->value('title');
                    } else {
                        $groupName = '--';
                    }
                    return $groupName;
                }
            ])->paginate($data['limit'], false, ['query' => $data])->append(['group_name']);
            $this->result(['list' => $list->items(), 'count' => $list->total()], 0, 'success', 'json');
        }
        return view();
    }

    // 添加管理员
    public function addAdmin()
    {
        if (request()->isAjax()) {
            $data = [
                'group_id' => input('group_id'),
                'username' => input('username'),
                'password' => input('password'),
                'nickname' => input('nickname'),
                'status' => input('status', 0)
            ];
            $validate = Validate::make([
                'group_id|角色' => 'require',
                'username|用户名' => 'require|unique:admin',
                'nickname|昵称' => 'require'
            ]);
            if (!$validate->check($data)) {
                $this->result('', 0, $validate->getError(), 'json');
            } else {
                $addData = [
                    'username' => $data['username'],
                    'nickname' => $data['nickname'],
                    'status' => $data['status']
                ];
                if ($data['password']) {
                    $addData['password'] = md5($data['password']);
                }
                Db::startTrans();
                try {
                    $adminInfo = model('Admin')::create($addData);
                    $accessData = [
                        'uid' => $adminInfo['id'],
                        'group_id' => $data['group_id']
                    ];
                    model('AuthGroupAccess')::create($accessData);
                    Db::commit();
                } catch (Exception $e) {
                    Db::rollback();
                    $this->result('', 0, $e->getMessage(), 'json');
                }
                $this->result('', 1, '操作成功', 'json');
            }
        }
        $groupList = model('AuthGroup')::select();
        $viewData = [
            'groupList' => $groupList
        ];
        $this->assign($viewData);
        return view();
    }

    // 删除多个管理员
    public function delAdmins()
    {
        $data = [
            'admin_ids' => input('admin_ids')
        ];
        $validate = Validate::make([
            'admin_ids|管理员' => 'require'
        ]);
        if (!$validate->check($data)) {
            $this->result('', 0, $validate->getError(), 'json');
        } else {
            $adminIdArray = explode(',', $data['admin_ids']);
            $adminIdArray = array_diff($adminIdArray, config('auth.super_ids'));
            sort($adminIdArray);
            trace($adminIdArray, 'alert');
            Db::startTrans();
            try {
                model('Admin')::destroy(function ($query) use ($adminIdArray) {
                    $query->where('id', 'in', $adminIdArray);
                });
                Db::commit();
            } catch (Exception $e) {
                Db::rollback();
                $this->result('', 0, $e->getMessage(), 'json');
            }
            $this->result('', 1, '操作成功', 'json');
        }
    }

    // 设置管理（状态）
    public function setAdmin()
    {
        $data = [
            'status' => input('status'),
            'id' => input('id')
        ];
        if (in_array($data['id'], config('auth.super_ids'))) {
            $this->result('', 0, '不允许设置超级管理员', 'json');
        }
        $updateData = [
            'id' => $data['id'],
            'status' => $data['status']
        ];
        Db::startTrans();
        try {
            model('Admin')::update($updateData);
            Db::commit();
        } catch (Exception $e) {
            Db::rollback();
            $this->result('', 0, $e->getMessage(), 'json');
        }
        $this->result('', 1, '操作成功', 'json');
    }

    // 编辑管理员
    public function editAdmin()
    {
        if (request()->isAjax()) {
            $data = [
                'id' => input('id'),
                'group_id' => input('group_id'),
                'password' => input('password'),
                'nickname' => input('nickname'),
                'status' => input('status', 0)
            ];
            $validate = Validate::make([
                'group_id|角色' => 'require',
                'nickname|昵称' => 'require'
            ]);
            if (!$validate->check($data)) {
                $this->result('', 0, $validate->getError(), 'json');
            } else {
                $updateData = [
                    'id' => input('id'),
                    'nickname' => $data['nickname'],
                    'status' => $data['status']
                ];
                if ($data['password']) {
                    $updateData['password'] = md5($data['password']);
                }
                Db::startTrans();
                try {
                    $adminInfo = model('Admin')::update($updateData);
                    $accessData = [
                        'uid' => $adminInfo['id'],
                        'group_id' => $data['group_id']
                    ];
                    model('AuthGroupAccess')->save($accessData, ['uid' => $accessData['uid']]);
                    Db::commit();
                } catch (Exception $e) {
                    Db::rollback();
                    $this->result('', 0, $e->getMessage(), 'json');
                }
                $this->result('', 1, '操作成功', 'json');
            }
        }
        $groupList = model('AuthGroup')::select();
        $adminInfo = model('Admin')::get(input('id'))->withAttr([
            'group_id' => function ($value, $info) {
                $groupId = model('AuthGroupAccess')::where('uid', $info['id'])->value('group_id');
                return $groupId;
            }
        ])->append(['group_id']);
        $viewData = [
            'groupList' => $groupList,
            'adminInfo' => $adminInfo
        ];
        $this->assign($viewData);
        return view();
    }

    // 角色列表
    public function roleList()
    {
        if (request()->isPost()) {
            $list = model('AuthGroup')->paginate(input('limit'), false, ['query' => input()]);
            $this->result(['list' => $list->items(), 'count' => $list->total()], 0, 'success', 'json');
        }
        return view();
    }

    // 添加角色
    public function addRole()
    {
        if (request()->isPost()) {
            $data = [
                'title' => input('title'),
                'rules' => input('rules')
            ];
            $validate = Validate::make([
                'title|角色名' => 'require|unique:auth_group',
                'rules|权限' => 'require'
            ]);
            if (!$validate->check($data)) {
                $this->result('', 0, $validate->getError(), 'json');
            } else {
                $addData = [
                    'title' => $data['title'],
                    'rules' => $data['rules']
                ];
                Db::startTrans();
                try {
                    model('AuthGroup')::create($addData);
                    Db::commit();
                } catch (Exception $e) {
                    Db::rollback();
                    $this->result('', 0, $e->getMessage(), 'json');
                }
                $this->result('', 1, '操作成功', 'json');
            }
        }
        $oneMenuList = model('AuthRule')->field(['id', 'title'])->where('pid', 0)->order('sort')->withAttr([
            'spread' => function () {
                return true;
            },
            'children' => function ($value, $info) {
                $menuList = model('AuthRule')->field(['id', 'title'])->where('pid', $info['id'])->order('sort')->select();
                return $menuList;
            }
        ])->select()->append(['spread', 'children']);
        $viewData = [
            'oneMenuList' => $oneMenuList
        ];
        $this->assign($viewData);
        return view();
    }

    // 删除多个角色
    public function delRoles()
    {
        $data = [
            'role_ids' => input('role_ids')
        ];
        $validate = Validate::make([
            'role_ids|角色' => 'require'
        ]);
        if (!$validate->check($data)) {
            $this->result('', 0, $validate->getError(), 'json');
        } else {
            $roleIdArray = explode(',', $data['role_ids']);
            Db::startTrans();
            try {
                model('AuthGroup')::destroy(function ($query) use ($roleIdArray) {
                    $query->where('id', 'in', $roleIdArray);
                });
                Db::commit();
            } catch (Exception $e) {
                Db::rollback();
                $this->result('', 0, $e->getMessage(), 'json');
            }
            $this->result('', 1, '操作成功', 'json');
        }
    }

    // 编辑角色
    public function editRole()
    {
        if (request()->isPost()) {
            $data = [
                'id' => input('id'),
                'title' => input('title'),
                'rules' => input('rules')
            ];
            $validate = Validate::make([
                'title|角色名' => 'require|unique:auth_group',
                'rules|权限' => 'require'
            ]);
            if (!$validate->check($data)) {
                $this->result('', 0, $validate->getError(), 'json');
            } else {
                $updateData = [
                    'id' => input('id'),
                    'title' => $data['title'],
                    'rules' => $data['rules']
                ];
                Db::startTrans();
                try {
                    model('AuthGroup')::update($updateData);
                    Db::commit();
                } catch (Exception $e) {
                    Db::rollback();
                    $this->result('', 0, $e->getMessage(), 'json');
                }
                $this->result('', 1, '操作成功', 'json');
            }
        }
        $data = [
            'id' => input('id')
        ];
        $roleInfo = model('AuthGroup')->where($data)->withAttr([
            'rules' => function ($value, $info) {
                $oneRules = model('AuthRule')->where(['pid' => 0])->column('id');
                $rules = explode(',', $value);
                return implode(',', array_diff($rules, $oneRules));
            }
        ])->find();
        $oneMenuList = model('AuthRule')->field(['id', 'title'])->where('pid', 0)->order('sort')->withAttr([
            'spread' => function () {
                return true;
            },
            'children' => function ($value, $info) {
                $menuList = model('AuthRule')->field(['id', 'title'])->where('pid', $info['id'])->order('sort')->select();
                return $menuList;
            }
        ])->select()->append(['spread', 'children']);
        $viewData = [
            'roleInfo' => $roleInfo,
            'oneMenuList' => $oneMenuList
        ];
        $this->assign($viewData);
        return view();
    }
}
